package com.kaibes.module.email.sender;

import org.simplejavamail.api.mailer.Mailer;
import org.simplejavamail.mailer.MailerBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import com.kaibes.web.json.JsonConfig;

@Configuration
public class MailConfig implements InitializingBean {

    @Value("${kaibes.module.email.username:}")
    private String username;
    @Value("${kaibes.module.email.password:}")
    private String password;
    @Value("${kaibes.module.email.host:}")
    private String host;
    @Value("${kaibes.module.email.port:25}")
    private int port;

    @Autowired
    private JsonConfig jsonConfig;
    @Autowired
    private SenderInfo senderInfo;
    @Autowired
    private MailSenderService mailSenderService;
    
    public String getUsername() {
        return senderInfo.getUsername();
    }

    public Mailer createMailer() {
        return MailerBuilder.withSMTPServer(senderInfo.getHost(), senderInfo.getPort(), senderInfo.getUsername(),
                senderInfo.getPassword()).buildMailer();
    }

	@Override
	public void afterPropertiesSet() throws Exception {
		jsonConfig.addXssIgnore("title");
    	jsonConfig.addXssIgnore("emailContent");
    	jsonConfig.addXssIgnore("html");
        
        SenderInfo temp = mailSenderService.get();
        if (temp == null) {
            senderInfo.setUsername(username);
            senderInfo.setPassword(password);
            senderInfo.setHost(host);
            senderInfo.setPort(port);
            mailSenderService.save(senderInfo);
        } else {
            senderInfo.setHost(temp.getHost());
            senderInfo.setPort(temp.getPort());
            senderInfo.setUsername(temp.getUsername());
            senderInfo.setPassword(temp.getPassword());
        }
	}

}
